package com.pet.shop.controller;

import com.pet.config.SessionConstants;
import com.pet.shop.entity.user.SysUser;
import com.pet.shop.service.user.ISysUserService;
import com.pet.shop.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller()
@RequestMapping("/web")
public class MainWebController {

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 进入主页
     * @return
     */
    @RequestMapping("index")
    public ModelAndView index(){
        return new ModelAndView("manage/index");
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping("login")
    public ModelAndView login(HttpServletRequest request, String loginName, String password){
        if(StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)){
            return new ModelAndView("manage/login");
        }
        SysUser sysUser = sysUserService.queryByLoginName(loginName);
        if(sysUser == null){
            return new ModelAndView("manage/login").addObject("msg","用户名或者密码错误").addObject("loginName", loginName);
        }
        if(!MD5Util.md5(password).equalsIgnoreCase(sysUser.getPassword())){
            return new ModelAndView("manage/login").addObject("msg","用户名或者密码错误").addObject("loginName", loginName);
        }
        request.getSession().setAttribute(SessionConstants.USER_SESSION_KEY, sysUser);
        SysUser sysUser2 = new SysUser();
        sysUser2.setId(sysUser.getId());
        sysUser2.setLastLoginTime(new Date());
        sysUserService.updateEntity(sysUser2);
        return new ModelAndView("redirect:/web/index");
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping("logout")
    public ModelAndView logout(HttpServletRequest request){
        request.getSession().removeAttribute(SessionConstants.USER_SESSION_KEY);
        return new ModelAndView("manage/login");
    }
}
